package com.yeyks.controller.hotel;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.base.PageResult;
import com.yeyks.common.dto.mq.EsUpdateMessage;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.cnhotel.CnHotelListParam;
import com.yeyks.common.result.cnhotel.CnHotelListResultCount;
import com.yeyks.common.result.cnhotel.ExportCnHotelResult;
import com.yeyks.common.utils.JsonUtils;
import com.yeyks.common.utils.Splitters;
import com.yeyks.common.utils.excel.ExcelUtil;
import com.yeyks.commonReference.append.mongodb.entity.CnHotelImageMongoEntity;
import com.yeyks.commonReference.append.mongodb.entity.CnRoomImageMongoEntity;
import com.yeyks.commonReference.append.mongodb.service.CnHotelImageMongoMongoService;
import com.yeyks.commonReference.append.mongodb.service.CnRoomImageMongoMongoService;
import com.yeyks.commonReference.append.rocketmq.service.producer.MQProducerService;
import com.yeyks.hotel.dal.domain.HotelBlackList;
import com.yeyks.hotel.service.HotelBlackListService;
import com.yeyks.search.constants.EsIndexConstant;
import com.yeyks.search.pojo.result.hotel.EsHotelInfoDetailVo;
import com.yeyks.search.service.ElasticSearchService;
import com.yeyks.search.service.MySearchService;
import com.yeyks.search.service.hotel.EsImportHotelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author fuchangshuai
 * @since 2019-07-03
 */
@Api(tags = "CN酒店模块")
@Slf4j
@RestController
@RequestMapping(value = "/cn/hotel")
public class CnHotelController {

    @Autowired
    private MySearchService mySearchService;
    @Autowired
    private ElasticSearchService elasticSearchService;
    @Autowired
    private EsImportHotelService esImportHotelService;
    @Autowired
    private CnHotelImageMongoMongoService cnHotelImageMongoMongoService;
    @Autowired
    private CnRoomImageMongoMongoService cnRoomImageMongoMongoService;
    @Autowired
    private HotelBlackListService hotelBlackListService;
    @Autowired
    private MQProducerService mqProducerService;

    @ApiOperation(value = "CN酒店模块 --> 列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public AjaxResponseBody<CnHotelListResultCount> list(CnHotelListParam param) {
        CnHotelListResultCount cnHotelListResultCount = mySearchService.searchCnHotel(param);
        return AjaxResponseBody.success(cnHotelListResultCount);
    }

    @ApiOperation(value = "CN酒店模块 --> 导出cn酒店", notes = "导出cn酒店")
    @PostMapping(value = "/export")
    public void export(@Validated CnHotelListParam param, HttpServletResponse response) {
        List<ExportCnHotelResult> exportCnHotelResult = mySearchService.exportCnHotel(param);
        ExcelUtil.disposeWriteExcelWithSheets(response, exportCnHotelResult, new ExportCnHotelResult());
    }

    @ApiOperation(value = "CN酒店模块 --> 详情", response = EsHotelInfoDetailVo.class)
    @ApiImplicitParam(paramType = "query", name = "sourceId", value = "酒店id", dataType = "String")
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public AjaxResponseBody<EsHotelInfoDetailVo> detail(String sourceId) {
        return AjaxResponseBody.success(mySearchService.searchCnHotelDetail(sourceId));
    }

    @ApiOperation(value = "CN酒店模块 --> 拉黑列表", response = HotelBlackList.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态，0无效，1有效，不传查询全部", dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "酒店名称", dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "pageNo", value = "当前页", dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "页码", dataType = "int"),
    })
    @RequestMapping(value = "/out/list", method = RequestMethod.POST)
    public AjaxResponseBody<PageResult<HotelBlackList>> outList(@RequestParam(name = "status", required = false) Integer status,
                                                                @RequestParam(name = "name", required = false) String name,
                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<HotelBlackList> wrapper = new QueryWrapper<HotelBlackList>().orderByDesc(HotelBlackList.CREATE_TIME);
        if (null != status) {
            wrapper.eq(HotelBlackList.STATUS, status);
        }
        if (StrUtil.isNotBlank(name)) {
            wrapper.like(HotelBlackList.SOURCE_NAME, name);
        }
        PageHelper.startPage(pageNo, pageSize);
        PageResult<HotelBlackList> pageResult = PageResult.getPageResult(hotelBlackListService.list(wrapper));
        return AjaxResponseBody.success(pageResult);
    }

    @ApiOperation(value = "CN酒店模块 --> 拉黑")
    @ApiImplicitParam(paramType = "query", name = "docId", value = "文档id", dataType = "String")
    @RequestMapping(value = "/out", method = RequestMethod.POST)
    public AjaxResponseBody<Boolean> out(String docId) {
        Arguments.isTrue(StrUtil.isBlank(docId), "文档id不能为空");
        EsHotelInfoDetailVo data = mySearchService.searchCnHotelByHotelId(docId);
        Arguments.beanIsNull(data, "该对应酒店不存在");
        //查询该酒店是否已在黑名单，存在修改状态，不存在拉黑
        HotelBlackList one = hotelBlackListService.getOne(new QueryWrapper<HotelBlackList>().eq(HotelBlackList.SOURCE_ID, data.getSourceId()).eq(HotelBlackList.SOURCE_TYPE, data.getSourceType()).last("limit 1"));
        if (null != one) {
            one.setStatus(1);
            Arguments.isFalse(hotelBlackListService.updateById(one), "拉黑异常");
            return AjaxResponseBody.success(true);
        }
        if (!hotelBlackListService.save(new HotelBlackList(null, data.getSourceId(), data.getName(), data.getSourceType(), 1, new Date()))) {
            throw new ServiceException("移入黑名单异常");
        }
        DeleteResponse response = elasticSearchService.deleteDocument(EsIndexConstant.INDEX_HOTEL2, docId);
        Arguments.beanIsNull(response, "移入黑名单异常");
        return AjaxResponseBody.success(true);
    }

    @ApiOperation(value = "CN酒店模块 --> 取消拉黑")
    @ApiImplicitParam(paramType = "query", name = "id", value = "id", dataType = "int")
    @RequestMapping(value = "/cancel/out", method = RequestMethod.POST)
    public AjaxResponseBody<Boolean> cancelOut(Integer id) {
        Arguments.intIsNull(id, "id不能为空");
        HotelBlackList byId = hotelBlackListService.getById(id);
        Arguments.beanIsNull(byId, "该记录不存在");
        byId.setStatus(0);
        if (!hotelBlackListService.updateById(byId)) {
            throw new ServiceException("移除黑名单异常");
        }
        mqProducerService.sendEsUpdate(new EsUpdateMessage("hotel", "cn", Lists.newArrayList(byId.getSourceId())), 0);
        return AjaxResponseBody.success(true);
    }

    @ApiOperation(value = "CN酒店模块 --> 修改酒店图片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "sourceId", value = "酒店id", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "urls", value = "图片链接(逗号隔开)", dataType = "String"),
    })
    @RequestMapping(value = "/update/image", method = RequestMethod.POST)
    public AjaxResponseBody<Boolean> updateImage(@RequestParam(name = "sourceId") String sourceId,
                                                 @RequestParam(name = "urls") String urls) {
        Arguments.strIsNull(sourceId, "酒店id不能为空");
        Arguments.strIsNull(urls, "图片链接不能为空");
        String imgUrlList = JsonUtils.addJsonList("imgUrlList", Splitters.splitToString(urls, Splitters.COMMA));
        Boolean flag = esImportHotelService.updateHotelImage(sourceId, imgUrlList);
        log.info("酒店图片更新结果 = {}", flag);
        cnHotelImageMongoMongoService.save(new CnHotelImageMongoEntity(sourceId, imgUrlList));
        return AjaxResponseBody.success(flag);
    }

    @ApiOperation(value = "CN酒店模块 --> 修改房间图片")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "hotelSourceId", value = "酒店id", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "roomSourceId", value = "房间id", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "urls", value = "图片链接(逗号隔开)", dataType = "String"),
    })
    @RequestMapping(value = "/update/room/image", method = RequestMethod.POST)
    public AjaxResponseBody<Boolean> updateRoomImage(@RequestParam(name = "hotelSourceId") String hotelSourceId,
                                                     @RequestParam(name = "roomSourceId") String roomSourceId,
                                                     @RequestParam(name = "urls") String urls) {
        Arguments.strIsNull(hotelSourceId, "酒店id不能为空");
        Arguments.strIsNull(roomSourceId, "房间id不能为空");
        Arguments.strIsNull(urls, "图片链接不能为空");
        String imgUrlList = JsonUtils.addJsonList("imgUrlList", Splitters.splitToString(urls, Splitters.COMMA));
        Boolean flag = esImportHotelService.updateRoomImage(roomSourceId, imgUrlList);
        log.info("房间图片更新结果 = {}", flag);
        cnRoomImageMongoMongoService.save(new CnRoomImageMongoEntity(roomSourceId, hotelSourceId, imgUrlList));
        return AjaxResponseBody.success(flag);
    }


}